import Toast from "tdesign-miniprogram/toast";
import { authByWechat, authByPhone, setSession } from "../../api/auth";

Page({
  data: {
    agreed: true,
    loginType: "wechat", // 'wechat' or 'sms'
    phone: "", // Keep phone and phoneError for onSmsLogin validation
    phoneError: false,
    code: "",
    showBindPopup: false,
    openid: "",
  },
  onShow() {
    console.log("====login page load=======");
  },
  onAgreeChange(e) {
    const { checked } = e.detail;
    this.setData({
      agreed: checked,
    });
  },
  switchLoginType() {
    this.setData({
      loginType: this.data.loginType === "wechat" ? "sms" : "wechat",
    });
  },
  onWechatLogin() {
    if (!this.data.agreed) {
      this.showToast({
        title: "请先阅读并同意协议",
        icon: "none",
      });
      return;
    }
    if (this.data.openid) {
      // 用户未绑定手机号，弹起绑定弹窗
      this.setData({
        showBindPopup: true,
        openid: this.data.openid,
      });
      return;
    }

    wx.login({
      success: async (res) => {
        if (!res.code) {
          console.log("登录失败！" + res.errMsg);
          showToast({
            title: "获取登录凭证失败",
            icon: "none",
          });
          return;
        }
        try {
          // Use the post helper
          const requestRes = await authByWechat(res.code);
          console.log("登录:", requestRes);
          if (requestRes.error) {
            showToast({
              title: requestRes.error.message || "登录失败",
              icon: "error",
            });
          }
          const { user, accessToken } = requestRes.data;

          if (user?.phone && accessToken) {
            // 设置会话状态
            this.onLoginSuccess(requestRes.data);
            return;
          }
          setSession(accessToken);
          // 用户未绑定手机号，弹起绑定弹窗
          this.setData({
            showBindPopup: true,
            openid: user.wechatId,
          });
        } catch (error) {
          console.error("请求失败", error);
          showToast({
            title: "网络错误，请稍后重试",
            icon: "none",
          });
        }
      },
      fail(err) {
        console.error("wx.login 接口调用失败", err);
        showToast({
          title: "微信登录失败",
          icon: "none",
        });
      },
    });
  },
  showToast(options = {}) {
    Toast({
      context: this,
      selector: "#t-toast",
      message: options.title,
    });
  },
  async onSmsLogin() {
    const { phone, phoneError, code, agreed } = this.data;
    if (!agreed) {
      this.showToast({ title: "请先阅读并同意协议", icon: "none" });
      return;
    }
    if (!phone) {
      this.showToast({ title: "请输入手机号", icon: "none" });
      return;
    }
    if (phoneError) {
      this.showToast({ title: "手机号格式不正确", icon: "none" });
      return;
    }
    if (!code) {
      this.showToast({ title: "请输入验证码", icon: "none" });
      return;
    }

    const res = await authByPhone({
      phone,
      code,
    });
    if (res.error) {
      this.showToast({
        title: res.error.message || "登录失败",
        icon: "error",
      });
      return;
    }
    this.onLoginSuccess(res.data);
  },
  navigateToAgreement() {
    wx.navigateTo({
      url: "/pages/agreement/agreement",
    });
  },
  onPhoneCodeInputChange(e) {
    const { phone, code, phoneError } = e.detail;
    this.setData({
      phone,
      code,
      phoneError,
    });
  },

  async onLoginSuccess(data = {}) {
    const { accessToken, user } = data;
    // 设置会话状态
    const isDone = setSession(accessToken);

    if (!isDone) {
      this.showToast({ title: "登录失败", icon: "none" });
      return null;
    }

    if (user) {
      const app = getApp();
      app.globalData.userInfo = user;
      if (!app.globalData.spotId) {
        await app.initSpotData();
      }
    }

    wx.showToast({
      title: "登录成功",
      icon: "success",
      success: () => {
        wx.navigateBack();
      },
    });
  },

  onBindClose() {
    this.setData({ showBindPopup: false });
  },

  onBindSuccess(data = {}) {
    console.log("onBindSuccess", data);
    wx.showToast({
      title: "绑定成功",
      icon: "success",
      success: () => {
        wx.navigateBack();
      },
    });
    // // 绑定成功后，可以进行页面跳转等操作
    // if (data.accessToken) {
    //   this.onLoginSuccess(data);
    // }
  },
});
